var form = layui.form, upload = layui.upload,laydate=layui.laydate, deleteIds = [], table = layui.table, $ = layui.jquery, bankAccountList = [], setIdList = [], id = getQueryVariable("id");

$('#editor-form').find('input,textarea,select').attr('disabled',true);
//表单初始值
if (id != "") {
    form.val("editor-form", {
        "receiptnumber": "初始值",
    })
}

let tempDetail = [];
let annexList = [];
let paymentDetail = [];
//操作日志数据
let operationLog = [];
$(document).ready(function () {
    //1.获取详情信息
    getDetailInfo();

    table.reload('maininformationtableid',{data:tempDetail});
    table.reload('realpaysubsidiarytableid',{data:paymentDetail});
    table.reload('attachmenttableid',{data:annexList});
    table.reload('logtableid',{data:operationLog});
});

function getDetailInfo() {
    //获取详情信息
    $.ajax({
        url:"payment/detail?id="+id,
        async:false,
        success:function(res){
            if(res.status == 200){
                //主表信息赋值
                if(null != res.data){
                    //主表数据
                    let vo =  res.data;
                    //表单赋值
                    form.val("editor-form", {
                        "id" : vo.id,
                        "billNo" : vo.billNo,
                        "time" : vo.time,
                        "supplierName" : vo.supplierName,
                        "bankName" : vo.bankName,
                        "bankAccount" : vo.bankAccount,
                        "typeStr" : vo.typeStr,
                        "currency" : vo.currency,
                        "usdRate" : vo.usdRate,
                        "rmbRate" : vo.rmbRate,
                        "amount" : vo.amount,
                        "companyName" : vo.companyName,
                        "operationNo" : vo.operation,
                        "memo" : vo.memo
                    });

                    //根据制单公司编码获取对应付款银行信息
                    getBankInfo(vo.companyCode);

                    //产品明细数据
                    tempDetail = res.data.detailList;

                    //实付明细数据
                    if(res.data.actuallyList){
                        paymentDetail = res.data.actuallyList;
                        //判断是否已经全部实付,如果没有，对应新增一条实付明细
                        let tempActuallyList = [];
                        for(let i in tempDetail){
                            let amountSum = 0;
                            for(let j in paymentDetail){
                                if(tempDetail[i]["id"] === paymentDetail[j]["detailId"]){
                                    amountSum = new BigNumber(amountSum).plus(paymentDetail[j]["amount"]);
                                }
                            }
                            let applicationAmount = tempDetail[i]["applicationAmount"];
                            let flag = new BigNumber(amountSum).comparedTo(new BigNumber(applicationAmount)) === -1
                            if(flag){
                                let lastAmount = new BigNumber(applicationAmount).minus(amountSum).dp(4, BigNumber.ROUND_HALF_UP).toString();
                                let temp = {
                                    "parentId" : tempDetail[i]["parentId"],
                                    "detailId" : tempDetail[i]["id"],
                                    "contractNo" : tempDetail[i]["contractNo"],
                                    "invoiceNumber" : tempDetail[i]["invoiceNumber"],
                                    "purchaseNo" : tempDetail[i]["purchaseNo"],
                                    "time" : currentDate,
                                    "bankName" : bankAccountList[0].name,
                                    "account" : bankAccountList[0].bankAccount,
                                    "amount" : lastAmount,
                                    "operator" : user.name,
                                    "operationCode" : user.code
                                }
                                tempActuallyList.push(temp);
                            }
                        }
                        if(tempActuallyList.length > 0){
                            paymentDetail.push.apply(paymentDetail, tempActuallyList);
                        }
                    }else{
                        for(let i in tempDetail){
                            let temp = {
                                "parentId" : vo.id,
                                "detailId" : tempDetail[i]["id"],
                                "contractNo" : tempDetail[i]["contractNo"],
                                "invoiceNumber" : tempDetail[i]["invoiceNumber"],
                                "purchaseNo" : tempDetail[i]["purchaseNo"],
                                "time" : currentDate,
                                "bankName" : bankAccountList[0].name,
                                "account" : bankAccountList[0].bankAccount,
                                "amount" : tempDetail[i]["applicationAmount"],
                                "operator" : user.name,
                                "operationCode" : user.code
                            }
                            paymentDetail.push(temp);
                        }
                    }
                    for(let i in paymentDetail){
                        let tempId = GenNonDuplicateID(3) + (i+1);
                        paymentDetail[i]["tempId"] = tempId;
                    }

                    //附件
                    if(res.data.annexList){
                        annexList = res.data.annexList;
                    }

                    //日志
                    if(!isEmpty(res.data.logList) && res.data.logList.length > 0){
                        operationLog = res.data.logList;
                    }

                }
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

function getBankInfo(code) {
    //获取银行账号
    $.ajax({
        url:"receivePayment/getBankAccountInfo?code=" + code,
        async:false,
        success:function(res){
            if(res.status == 200){
                //银行信息
                bankAccountList = res.data.bankAccountList;
            }
        }
    });
}

//监听提交
form.on('submit(form-element)', function (data) {
    let indexsl = 0;
    //获取实付数据
    let actuallyList = table.cache["realpaysubsidiarytableid"];
    $.each(actuallyList,function(index,value){
        if(typeof (actuallyList[index]["time"])== "undefined" || actuallyList[index]["time"]==""){
            layer.msg("实付明细表第"+(index+1)+"条实付日期不能为空");
            indexsl++;
            return false;
        }else if(typeof (actuallyList[index]["amount"])== "undefined" || actuallyList[index]["amount"]==""){
            layer.msg("实付明细表第"+(index+1)+"条实付金额不能为空");
            indexsl++;
            return false;
        }
    });
    if(indexsl == 0){
        //向后台组装数据
        let req = data.field;

        req["actuallyList"] = actuallyList;

        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];

        req["annexList"] = annexReqs;

        req["deleteIds"] = deleteIds;
        let result = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:result,
            url:"payment/addActually",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        let index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    },1000);
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });
    }
    return false;
});

    table.render({
        elem: '#maininformation',
        id: 'maininformationtableid',
        totalRow: true,
        cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'invoiceNumber', width: 120, title: '发票号码', sort: true},
            {field: 'contractNo', width: 120, title: '外销合同号', sort: true},
            {field: 'purchaseNo', width: 120, title: '采购单号', sort: true},
            {field: 'typeName', width: 280, title: '付款类型'},
            {field: 'berPersonName', width: 180, title: '承担人员'},
            {field: 'amountsPayable', width: 120, title: '应付金额', sort: true, totalRow: true},
            {field: 'applicationAmount', width: 80, title: '申请金额', totalRow: true},
            {field: 'totalApplication', width: 120, title: '已申请合计', sort: true, totalRow: true},
            {field: 'claimAmount', width: 120, title: '索赔金额', totalRow: true},
            {field: 'allocatedAmount', width: 120, title: '已分摊金额', sort: true, totalRow: true},
            {field: 'unallocatedAmount', width: 120, title: '未分摊金额', sort: true, totalRow: true},
            {field: 'purchasePaidAmount', width: 120, title: '采购已付款金额', sort: true, totalRow: true},
            {field: 'totalPurchaseAmount', width: 120, title: '采购合同总额', sort: true, totalRow: true},
            {field: 'totalInvoiceAmount', width: 120, title: '发票合同总额', sort: true, totalRow: true},
            {field: 'invoicePaidAmount', width: 120, title: '发票已付款金额', sort: true, totalRow: true},
            {field: 'specialNote', width: 80, title: '特殊备注'},
            {field: 'carryDate', width: 120, title: '出运日期', sort: true},
            {field: 'customerCode', width: 120, title: '客户代码', sort: true},
            {field: 'saleAmountReceived', width: 120, title: '外销已收款金额', sort: true, totalRow: true},
            {field: 'supplierAccountPeriod', width: 120, title: '供应商账期', sort: true},
            {field: 'saleAccountPeriod', title: '外销客户账期', width: 120},
            {field: 'priceTermsName', title: '外销价格术语', width: 120},
        ]],
        height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        }
    });


table.render({
    elem: '#realpaysubsidiary'
    ,toolbar:"#realpaysubsidiarytoolbar"
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
        ,{field:'contractNo',width:'150', title:'外销合同号',edit: 'text'}
        ,{field:'invoiceNumber',width:'150', title:'发票编号',edit: 'text'}
        ,{field:'purchaseNo',width:'150', title:'采购单号',edit: 'text'}
        ,{field:'time',width:'150', title:'实付日期', templet:function(d){
            return '<input type="text" value="'+d.time+'"  class="layui-input layui-input-date">';
        }}
        ,{field:'bankName',width:'200', title:'付款银行', templet: '#bankNameSelect'}
        ,{field:'account',width:'200', title:'付款账号', templet: '#accountSelect'}
        ,{field:'amount',width:'100', title:'实付金额',edit: 'text', totalRow: true}
        ,{field:'remark',width:'250', title:'实付备注',edit: 'text'}
        ,{field:'operator',width:'150', title:'操作员名称'}
    ]]
    ,id: 'realpaysubsidiarytableid'
    ,height: 380
    ,page: false
    ,limit: Number.MAX_VALUE
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')

        $(".layui-input-date").each((i,e)=>{
            laydate.render({
                elem:e,
                format: 'yyyy-MM-dd',
                type: 'date',
                trigger: 'click',
                theme: '#393D49',
                calendar: true,
                done(data){
                    let tableData = table.cache["realpaysubsidiarytableid"];
                    if(0 === i){
                        for(let j in tableData){
                            tableData[j]["time"] = data;
                        }
                    }else {
                        tableData[i]["time"] = data;
                    }

                    table.reload('realpaysubsidiarytableid',{data:tableData});
                }
            });
        })

        for(let i in bankAccountList){
            $(".bankName").append("<option value=\"" + bankAccountList[i].name + "\">" + bankAccountList[i].name + "</option>");
            $(".account").append("<option value=\"" + bankAccountList[i].bankAccount + "\">" + bankAccountList[i].bankAccount + "</option>");
        }

        for (var i = 0; i < res.data.length; i++) {
            let tempId = res.data[i].tempId;
            if(!isEmpty(res.data[i].bankName)){
                $("#bankName_" + tempId).val(res.data[i].bankName);
            }else {
                $("#bankName_" + tempId).val(bankAccountList[0].name);
            }

            if(!isEmpty(res.data[i].account)){
                $("#account_" + tempId).val(res.data[i].account);
            }else {
                $("#account_" + tempId).val(bankAccountList[0].bankAccount);
            }
        }


        form.render('select');
    }
});

//根据银行名称获取银行账号
function getBankAccountByBankName(bankName){
    let bankAccount = "";
    for(let i in bankAccountList){
        if(bankAccountList[i].name === bankName){
            bankAccount = bankAccountList[i].bankAccount;
            break;
        }
    }
    return bankAccount;
}

form.on("select(bankNameSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["realpaysubsidiarytableid"];
    let bankAccount = getBankAccountByBankName(data.value);
    if(dataIndex === "0"){
        $.each(tableData, function (index, value) {
            tableData[index]["bankName"] = data.value;
            tableData[index]["account"] = bankAccount;
        });
    }else {
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["bankName"] = data.value;
                tableData[index]["account"] = bankAccount;
                return;
            }
        });
    }
    table.reload('realpaysubsidiarytableid',{data:tableData})
});


//根据银行账号获取银行名称
function getBankNameByBankAccount(bankAccount){
    let bankName = "";
    for(let i in bankAccountList){
        if(bankAccountList[i].bankAccount === bankAccount){
            bankName = bankAccountList[i].name;
            break;
        }
    }
    return bankName;
}

form.on("select(accountSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["realpaysubsidiarytableid"];
    let bankName = getBankNameByBankAccount(data.value);
    if(dataIndex === "0"){
        $.each(tableData, function (index, value) {
            tableData[index]["account"] = data.value;
            tableData[index]["bankName"] = bankName;
        });
    }else {
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["account"] = data.value;
                tableData[index]["bankName"] = bankName;
                return;
            }
        });
    }
    table.reload('realpaysubsidiarytableid',{data:tableData})
});



function productTableReload(){
    table.reload('realpaysubsidiarytableid',{
        data:table.cache.test,
        totalRow: true,
    })
}

table.on('edit(realpaysubsidiarytable)',function (obj) {
    let old = $(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if((obj.field== "amount")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    if(obj.field == "amount"){
        if(!checkAmount(obj)){
            obj.update({
                amount:old
            });
            $(this).val(old);
            return;
        }
    }

    //表单重载
    productTableReload();
});

function checkAmount(obj) {
    //明细id
    let id = obj.data["detailId"];
    //实付金额不能大于申请金额
    //获取申请金额
    let applicationAmount = 0;
    for(let i in tempDetail){
        if(tempDetail[i]["id"] === id){
            applicationAmount = tempDetail[i]["applicationAmount"];
            break;
        }
    }
    //获取实付数据
    let actuallyList = table.cache["realpaysubsidiarytableid"];
    //已实付金额
    let amountSum = 0;
    //实付临时id
    let tempId = obj.data["tempId"];
    for(let i in actuallyList){
        if(actuallyList[i]["detailId"] === id && actuallyList[i]["tempId"] != tempId){
            amountSum = new BigNumber(amountSum).plus(actuallyList[i]["amount"]);
        }
    }
    //加上本次金额
    amountSum = new BigNumber(amountSum).plus(obj.value);
    if(amountSum.comparedTo(applicationAmount) == 1){
        layer.msg("实付金额不能超过申请金额", {icon: 5});
        return false;
    }
    return true;
}

function tobottomfn(id){
    let d=$("[lay-id='"+id+"'] .layui-table-main").get(0)
    let h=d.scrollHeight
    d.scrollTo(0,h)
}

table.on('toolbar(realpaysubsidiarytable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'new':
            let oldData = table.cache["realpaysubsidiarytableid"];
            let data1={"id":oldData.length+1};
            oldData.push(data1);
            table.reload('realpaysubsidiarytableid',{data : oldData});
            tobottomfn("realpaysubsidiarytableid");
            break;
        case 'del':
            let data = checkStatus.data, delList = [];
            data.forEach(function(n,i){
                delList.push(n.tempId);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？', confirmInfo(3,6),function (index) {
                    let cbList = table.cache["realpaysubsidiarytableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                if (!isEmpty(cbList[i]["id"])) {
                                    deleteIds.push(cbList[i]["id"]);
                                }
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("realpaysubsidiarytableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;

        case 'setTimeAndBank':
            setIdList = [];
            let checkData = checkStatus.data;
            checkData.forEach(function (n, i) {
                setIdList.push(n.tempId);
            });
            if(isEmpty(setIdList)){
                layer.msg('请选择数据');
                break;
            }
            layer.open({
                title:'一键设置',
                type: 2,
                area: ['800px', '400px'],
                content: 'views/jsp/Money/tpl/setTimeAndBank.jsp?',
            });
            break;
    };
});

//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
    , done: function (res, index, upload) {
        let data = res.data;
        for(let i in data){
            let flag = true;
            for(let j in annexList){
                if(data[i].id == annexList[j].id){
                    flag = false;
                    break;
                }
            }
            if(flag){
                annexList.push(data[i]);
            }
        }
    }
});
upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexList.length; i++) {
                    if (annexList[i].id == id) {
                        annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
            });
    }
});

    //---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
              {field: 'operationType', title: '操作类型', fixed: true}
            , {field: 'operationName', title: '操作员'}
            , {field: 'operationTime', title: '操作日期'}
            , {field: 'operationContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}

let currentDate = getNowFormatDate(1);

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}